package com.example.supermonkeysm.security.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.supermonkeysm.dao.UserMapper;
import com.example.supermonkeysm.entity.User;
import com.example.supermonkeysm.security.dao.UsersRolesMapper;
import com.example.supermonkeysm.security.entity.DetailsUser;
import com.example.supermonkeysm.security.entity.UsersRoles;
import com.example.supermonkeysm.utils.Result;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("register")
public class RegisterController {
    @Resource
    UserMapper userMapper;
    @Resource
    UsersRolesMapper usersRolesMapper;


    @PostMapping
    public Result<?> register(@RequestBody DetailsUser detailsUser) {//@RequestParam为属性必填注释
        String username = detailsUser.getUsername();
        String password = detailsUser.getPassword();
        //判断输入框的值是否为空，若为空则报错
        if (username == null || StringUtils.isBlank(username)) return Result.error("用户名为空，请输入！");
        if (password == null || StringUtils.isBlank(password)) return Result.error("密码为空，请输入！");

        //判断数据库是否存在该用户
        MPJLambdaWrapper<User> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.eq(User::getUsername,username);
        //如果存在，则报错
        if (userMapper.selectOne(mpjLambdaWrapper) != null) return Result.error(username,"该用户已存在");


        //添加用户到数据库之前将密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        //添加用户到数据库User表
        User user = new User(username, bCryptPasswordEncoder.encode(password));
        int insert = userMapper.insert(user);
        if (insert != 1) return Result.error("注册失败，请联系管理员");
        //添加用户到数据库权限表
        UsersRoles usersRoles = new UsersRoles(user.getId());
        int insert2 = usersRolesMapper.insert(usersRoles);
        if (insert2 != 1) return Result.error("设置默认角色失败，请联系管理员");

        return Result.success("注册成功");
    }


}
